import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

const router = new Router({
  routes: [
    /*{
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    }*/
    {
      path: '/login',
      name: 'Login',
      component: () => import('../views/common/Login'),
      meta: {title: '登录'}
    },
    {
      path: '/',
      name: 'Home',
      component: () => import('../views/layout/Index'),
      children: [
        {
          path: '',
          name: 'HomeIndex',
          component: () => import('../views/index/Index')
        },
        {
          path: '/borrow',
          name: 'BorrowIndex',
          component: () => import('../views/borrow/Index')
        },
        {
          path: '/user',
          name: 'UserIndex',
          component: () => import('../views/user/Index'),
        },
      ]
    },
    {
      path: '/user',
      name: 'User',
      component: () => import('../views/layout/Default'),
      children: [
        {
          path: 'info',
          name: 'UserInfo',
          component: () => import('../views/user/Info')
        },
        {
          path: 'updatePwd',
          name: 'UpdatePwd',
          component: () => import('../views/user/UpdatePwd')
        },
        {
          path: 'service',
          name: 'Service',
          component: () => import('../views/user/Service')
        },
        {
          path: 'idea',
          name: 'Idea',
          component: () => import('../views/user/Idea')
        }
      ]
    },
    {
      path: '/book',
      name: 'Book',
      component: () => import('../views/layout/Default'),
      children: [
        {
          path: 'detail/:id',
          name: 'BookDetail',
          component: () => import('../views/book/Detail')
        }
      ]
    }
  ]
});

//全局路由前置守卫
router.beforeEach((to, from, next) => {
  //获取当前登录状态
  const token = window.localStorage.getItem('ba_user_token');
  if (!token && to.path !== '/login') return next('/login'); //不存在login

  //如果已登录
  if (token && (to.path === '/login' || to.path === '/regist')) return next('/user');

  /* 路由发生变化修改页面title */
  if (to.meta.title) {
    document.title = to.meta.title;
  }

  next();
});

export default router;
